/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.share;

import java.sql.*;
import java.util.*;
import javax.sql.DataSource;
import javax.naming.*;

/**
 *
 * @author NeaghFoz
 */
public class DBConnect {

    private Statement stmt = null;
    private ResultSet rs = null;

    public DBConnect() {
        try {
            Class.forName(("com.mysql.jdbc.Driver"));
        } catch (java.lang.ClassNotFoundException e) {
            System.err.println("opendb():" + e.getMessage());
        }
    }

    /**
     *  executeQuery
     *
     */
    public ArrayList executeQuery(DataSource source, String strSql) throws SQLException {
        Connection con = null;
        rs = null;
        ArrayList ArrayRs = new ArrayList();
        try {
            //InitialContext initCtx = new InitialContext();
            //source = (DataSource) initCtx.lookup("java:/comp/env/jdbc/connectionPool");
            con = source.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery(strSql);

            ResultSetMetaData rsmd = rs.getMetaData();
            int numberOfColumns = rsmd.getColumnCount();

            if (!ArrayRs.isEmpty()) {
                ArrayRs.clear();
            }
            while (rs.next()) {
                ArrayList arrlist = new ArrayList();
                for (int j = 1; j <= numberOfColumns; j++) {
                    String s = rs.getString(j);
                    if (s == null) {
                        s = "";
                    }
                    arrlist.add(s);
                }
                ArrayRs.add(arrlist);
            }
        } catch (Exception e) {
            System.out.println("query error:" + e.getMessage());
        } finally {
            if (stmt != null) {
                stmt.close();
            }
            if (con != null && !con.isClosed()) {
                con.close();
            }
        }
        return ArrayRs;
    }

    /**
     * executeInsert
     */
    public boolean executeInsert(DataSource source, String strSql) throws SQLException {
        Connection con = null;
        rs = null;
        try {
            //InitialContext initCtx = new InitialContext();
            //source = (DataSource) initCtx.lookup("java:/comp/env/jdbc/connectionPool");
            con = source.getConnection();
            stmt = con.createStatement();

            con.setAutoCommit(true);
            int i = stmt.executeUpdate(strSql);

            if (i == 1) {
                return (true);
            }
        } catch (Exception e) {
            System.out.println("Insert error:" + e.getMessage());
        } finally {
            if (stmt != null) {
                stmt.close();
            }
            if (con != null && !con.isClosed()) {
                con.close();
            }
        }
        return (false);
    }

    /**
     * executeUpdate
     */
    
}
